# -*- coding: utf-8 -*-
"""
****************************
@Time    : 2021/5/25 14:11
@Author  : Candy
@File    : user_serializer.py
****************************
"""
from flask_sqlalchemy import SQLAlchemy

from models.articles import Cate, Img
from models.users import User


class BaseArticle:

    def __init__(self, source_data, mode):
        self.source_data = source_data
        self.mode = mode
        self.__check()

    def __check(self):
        if self.mode not in ['many', 'single']:
            raise TypeError('模式错误，仅限many single')
        if self.mode == 'many' and not isinstance(self.source_data, list):
            raise TypeError('many模式下，应传入列表对象')
        if self.mode == 'single' and isinstance(self.source_data, list):
            raise TypeError('single模式下，应传入单个对象')

    def result(self):
        return self.many() if self.mode == 'many' else self.single()

    def many(self):
        arr = []
        for one_data in self.source_data:
            arr.append(self.handle(one_data))
        return arr

    def single(self):
        return self.handle(self.source_data)

    @staticmethod
    def handle(data):
        return None


class Simple(BaseArticle):

    def __init__(self, source_data, mode):
        super().__init__(source_data, mode)
        self.db = SQLAlchemy()

    def handle(self, data):
        a = data
        cate = self.db.session.query(Cate).filter(Cate.id == a.cate).first()
        return {
            "title": a.title,
            "aid": a.aid,
            "a_type": cate.cate_value,
            'is_public': a.is_public,
            'rate_star': a.rate_star,
            'view_count': a.view_count,
        }


class Detail(BaseArticle):

    def __init__(self, source_data, mode):
        super().__init__(source_data, mode)
        self.db = SQLAlchemy()

    def handle(self, data):
        a = data
        user_info = self.db.session.query(User).filter(User.id == a.user_id).first()
        cate = self.db.session.query(Cate).filter(Cate.id == a.cate).first()
        return {
            "title": a.title,
            "aid": a.aid,
            "a_type": cate.cate_value,
            "add_time": str(a.add_time),
            "user": user_info.m_dumps(),
            'rate_star': a.rate_star,
            'view_count': a.view_count,
            'tags': a.tags,
            'logo': self.db.session.query(Img).filter(Img.id == int(a.logo)).first().img_base64,
        }


